//
//  ViewController.swift
//  复制图层恒星旋转动画
//
//  Created by app on 2017/4/18.
//  Copyright © 2017年 app. All rights reserved.
//

import UIKit


class ViewController: UIViewController {
    
    let UISCREEN_WIDTH = UIScreen.main.bounds.width
    let UISCREEN_HEIGHT = UIScreen.main.bounds.height
    var replicatorLayer = CAReplicatorLayer()
    var iv_earth:UIImageView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let backImge = UIImageView(frame: CGRect(x: 0, y: 0,
                                                 width: UISCREEN_WIDTH,
                                                 height: UISCREEN_HEIGHT))
        backImge.image = #imageLiteral(resourceName: "background.jpg")
        
        view.addSubview(backImge)
        
        iv_earth  = UIImageView(frame: CGRect(x: (UISCREEN_WIDTH - 50) / 2 + 150,
                                              y: (UISCREEN_HEIGHT - 50) / 2,
                                              width: 50,
                                              height: 50))
        iv_earth?.image = #imageLiteral(resourceName: "earth.png")
        
        let iv_sun = UIImageView(frame: CGRect(x: 0,
                                               y: 0,
                                               width: 50,
                                               height: 50))
        iv_sun.center = view.center
        iv_sun.image = #imageLiteral(resourceName: "sun.png")
        replicatorLayer.addSublayer((iv_earth?.layer)!)
        replicatorLayer.addSublayer(iv_sun.layer)
    
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let path = UIBezierPath()
        path.addArc(withCenter: view.center, radius: 150, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true)
        path.close()
        
        let animation = CAKeyframeAnimation(keyPath: "position")
        animation.path = path.cgPath
        animation.duration = 10
        animation.repeatCount = MAXFLOAT
        replicatorLayer.instanceCount = 100
        replicatorLayer.instanceDelay = 0.2
        view.layer.addSublayer(replicatorLayer)
        iv_earth?.layer.add(animation, forKey: nil)
    }


}

